package com.example.demo.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.exception.ApiException;
import com.example.demo.util.JsonUtil;
import com.example.demo.util.ResultEntity;

/**
 * 全局异常处理器
 *
 * @author CatalpaFlat
 */
@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {
	/**
	 * 日志log
	 */
	private static Logger log = LoggerFactory.getLogger(CustomExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		// handler就是处理器适配器要执行的Handler对象(只有method)
		// 解析出异常类型。
		/* 使用response返回 */
		response.setStatus(HttpStatus.OK.value()); // 设置状态码
		response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
		response.setCharacterEncoding("UTF-8"); // 避免乱码
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		// 如果该 异常类型是系统 自定义的异常，直接取出异常信息。
		ApiException customException = null;
		log.error(ex.getMessage(), ex);
		try {
			if (ex instanceof ApiException) {
				customException = (ApiException) ex;

				String errorJson = JsonUtil
						.beanToJson(new ResultEntity<>(customException.getCode(), ((ApiException) ex).getMessage()));
				// 错误信息
				response.getWriter().write(errorJson);
			} else {
				String errorJson = JsonUtil.beanToJson(new ResultEntity<>("-1", ex.getMessage()));
				response.getWriter().write(errorJson);
			}
		} catch (IOException e) {
			log.error("与客户端通讯异常:" + e.getMessage(), e);
		}

		ModelAndView modelAndView = new ModelAndView();
		return modelAndView;
	}
}